from tools.sqpyfia.sqPyfia import sqPyfia
from tools.htmlout import *
from tools.pluginSkel import AttackPlugin
import sys
import dbus

class AttackMod_sqPySqlin(AttackPlugin):
    def __init__(self):
	# Name, variableSet ,iface, infoType, fields
	AttackPlugin.__init__(self,"pySQLin attacks",True,True,"tree",["Url","Variable","Method","Injection Type","DB Fingerprint","DB Error", "Send"])


    def transform_result(self, result, req):
	l = []
	url, all_sqli = result

	for var, method, itype, db, dberror in all_sqli:
	    if dberror is None: dberror = ''
	    if db is None: db= ''

	    l.append( (url, req.postdata,req.response.getCookie(), var, method, itype, db, dberror) )

	return l


    def process(self,req):
	sq=sqPyfia(req,self.LOG)
	sq.setThreaded(1)
	try:
	    sq.launch()

	    res=sq.getRAWResults()
	    xml=sq.getXMLResults()

	    if res:
		self.putRESULTS(res,sq.getRequestExample())
		self.xmlRESULTS.append(xml.childNodes[0].childNodes[0])

		bus = dbus.SessionBus()
		self.remote_object = bus.get_object("com.pysqlin.DBusServer",
					    "/ImportObject")
		iface = dbus.Interface(self.remote_object, "com.pysqlin.interface")
		for l in self.transform_result(res, req):
		    print l
		    iface.send_sqli(l)
	except Exception,a:
	    self.LOG.debug("SqlInj Engine: "+str(a)+" - "+"Fallo en SQL, REQ="+str(req))


    def getXML(self):
	return self.xmlRESULTS

    def getHTML(self):
	output=htmlout.html(title=self.pluginName+" results")

	for r in self.RESULTS:
	    t=htmlout.SqlTable()
	    t.setTitle(r[0])
	    for j in r:
		t.addRow(j)
	    output.appendTable(t)
	output.flush()

	return str(output)

